/*global $Client*/   
import React, { useState,useEffect } from 'react';
import { Upload, Button, Spin, message } from 'antd';
import { DownloadOutlined, UploadOutlined } from '@ant-design/icons';
import ExcelJS from 'exceljs';


//合同excel导入，可通用 excelImport_cn
const ExcelComponent = () => {
  const [loading, setLoading] = useState(false);

  const handleDownload = async () => {
    setLoading(true);
    // const link = 'https://files.zohopublic.com.cn/public/workdrive-public/download/rnv2n3a5984e6536f416da86f577a44385011?x-cli-msg={"linkId":"1nHCl5jq6Qp-31RIu","isFileOwner":false,"version":"2.0"}';
    
    var link = window.wdata?.templates_downloadurl;
    // console.log(crmdata);
    try {
      window.location.href = link;
    } catch (error) {
      console.error('下载文件失败:', error);
      message.error('下载文件失败！');
    }finally{
      setLoading(false);
    }
  };
  useEffect(() => {
    const initialize = async () => {
      await window.zohoReadyPromise;
      console.log("ZOHO is ready", window.ZOHO);
    };
    initialize();
  }, []);
  const handleImport = async(options) => {
    const { file, onSuccess, onError } = options;
    setLoading(true);
    const reader = new FileReader();
    reader.onload = async (e) => {
      try {
        const arrayBuffer = e.target.result;
        const workbook = new ExcelJS.Workbook();
        await workbook.xlsx.load(arrayBuffer);

        const worksheet = workbook.worksheets[0]; // 只处理第一个工作表
        const json = [];
        const headers = [];

        worksheet.eachRow((row, rowNumber) => {
          if (rowNumber === 1) {
            row.eachCell((cell) => {
              headers.push(cell.value);
            });
          } else {
            const rowData = {};
            row.eachCell((cell, colNumber) => {
              rowData[headers[colNumber - 1]] = cell.value;
            });
            json.push(rowData);
          }
        });

        console.log('文件上传成功:', json);
        setLoading(false);
        onSuccess('ok');
        message.success('文件上传成功！');
        $Client.close({"exceldata":json});
      } catch (error) {
        console.error('文件上传失败:', error);
        setLoading(false);
        onError(error);
        message.error('文件上传失败！');
      }
    };
    reader.onerror = (error) => {
      console.error('文件读取失败:', error);
      setLoading(false);
      onError(error);
      message.error('文件读取失败！');
    };
    reader.readAsArrayBuffer(file);
  };

  const handleClose = () => {
    $Client.close(); // 替换为适当的关闭窗口函数
  };

  return (
    <Spin spinning={loading}>
      <div style={{ padding: '20px', height: '100vh' }}>
        <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: '20px' }}>
          <Button type="text" onClick={handleClose} style={{ position: 'absolute', top: 10, right: 10, zIndex: 999 }}>
            X
          </Button>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-start', justifyContent: 'flex-start', marginBottom: '20px' }}>
          <Button type="link" onClick={handleDownload} icon={<DownloadOutlined />} style={{ marginBottom: 20 }}>
            下载 Excel 模板文件
          </Button>
          <Upload
            name="file"
            customRequest={handleImport}
            showUploadList={false}
            accept=".xlsx,.xls"
          >
            <Button type="primary" icon={<UploadOutlined />}>导入 Excel</Button>
          </Upload>
        </div>
      </div>
    </Spin>
  );
  
};

export default ExcelComponent;
